package labrom.usage.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import labrom.usage.shared.Udi;


public class ApiV1TestServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private PropsLoader propsLoader = new PropsLoader();
	
	@Override
	public void init() throws ServletException {
		super.init();
		try {
			InputStream input = getServletContext().getResourceAsStream("/WEB-INF/usagedata.properties");
			propsLoader.loadFromProperties(input);
		} catch (IOException e) {
			throw new ServletException("Failed to load usagedata.properties", e);
		}
	}


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ApiV1TestPath path = new ApiV1TestPath(req.getPathInfo());
		
		if("populate".equals(path.what)) {

			/* Populate with random data from 80 clients, 1000 usage data items */
			UUID[] guids = new UUID[80];
			for(int i = 0; i < guids.length; i ++)
				guids[i] = UUID.randomUUID();
			
			Udi[] udis = new Udi[1000];
			Random r = new Random();
			long now = System.currentTimeMillis();
			int days = 30;
			List<Integer> screenIds = new ArrayList<Integer>(propsLoader.getProps().screenCaptions.keySet());
			List<Integer> typeIds = new ArrayList<Integer>(propsLoader.getProps().typeCaptions.keySet());
			for(int i = 0; i < 1000; i ++) {
				UUID guid = guids[r.nextInt(guids.length)];
				Udi u = new Udi();
				u.setGuidMsb(guid.getMostSignificantBits());
				u.setGuidLsb(guid.getLeastSignificantBits());
				u.setAppVersion(path.appVersion);
				u.setTimestamp(now - (r.nextInt(days * 24 * 3600) * 1000));
				int screenId = screenIds.get(r.nextInt(screenIds.size()));
				int typeId = typeIds.get(r.nextInt(typeIds.size()));
				u.setTypeId(screenId * 1000000000000l + typeId * 1000000);
				udis[i] = u;
			}
			
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			boolean success = false;
			try {
//				Query delete = pm.newQuery(Udi.class);
//				delete.deletePersistentAll();
				pm.makePersistentAll(udis);
				success = true;
			} catch(Exception e) {
				// FIXME Logging?
			} finally {
				pm.close();
			}
			
			
			PrintWriter writer = resp.getWriter();
			writer.write(success ? String.valueOf(udis.length) : "0");
			writer.close();
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
	}

	
	
	
	
	
	

}
